package com.gitee.hifong45.annotations;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;

public class FLogPointcutAdvice implements MethodInterceptor {
    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        System.out.println("===================================== this is FLog =================");
        Method method = methodInvocation.getMethod();
        Class<?> clazz = method.getDeclaringClass();
        if(clazz.getDeclaredAnnotation(RestController.class) != null || clazz.getDeclaredAnnotation(Controller.class) != null){
            FLog FLog = method.getDeclaredAnnotation(FLog.class);
            int value = FLog.value();

            ServletRequestAttributes attrs = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
            if(attrs == null) {
                return null;
            }
            HttpServletRequest request = attrs.getRequest();
            // String uri = request.getRequestURI();

            String servletPath = request.getServletPath();
            Logger logger = LoggerFactory.getLogger(clazz);
            if(value == 0){
                logger.info("path: {}, args: {}", servletPath, Arrays.toString(methodInvocation.getArguments()));
                System.out.println("path: {}, args: {}" + servletPath + Arrays.toString(methodInvocation.getArguments()));
            }
            // long btime = System.currentTimeMillis();
            Object result = methodInvocation.proceed();
            return result;
        }
        return null;
    }
}
